'''
Created on Apr 3, 2012

@author: tel
'''
#site.addsitedir(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import site, os, shutil, threading, copy, time, numpy, sys, random, string
site.addsitedir('/home/tel/workspace/pmcce/src/')
#global vars: META, DB

from sqlalchemy import create_engine, MetaData, event
from sqlalchemy.orm import sessionmaker, scoped_session, mapper, relationship

import config
import rules
import levels

file_names = ('csa.dat')
rule_dict = {'csa.dat':rules.CSARule}

class FileList(object):
    def __init__(self, file_paths):
        self.file_paths = file_paths
        self.files = []
    
    def Open(self):
        for fi in self.file_paths:
            self.files.append(open(fi, 'r'))
    
    def Close(self):
        for fi in self.file_paths:
            fi.close()

def _fk_pragma_on_connect(dbapi_con, con_record):
    dbapi_con.execute('pragma foreign_keys=ON')

def MakeAncilDB(meta, db, session, csadir, lock, event):
    now = time.clock()
    data = {}
    file_list = FileList([os.path.join(csadir,'csa.dat')])
    file_list.Open()
    for fi in file_list.files:
        rule = rule_dict[fi.name.split('/')[-1]](fi)
        fi.close()
        data[rule.rtype] = rule.data
    levels.CSAData.Org(data)
    levels.CSAData.Table(meta=meta, db=db, standalone=True)
    levels.CSAData.SQLize()
    for instance in levels.CSAData.instances:
        session.add(instance)
    event.set()
    with lock:
        session.commit()
    print 'CSA db took %.3f' % (time.clock() - now)

if __name__ == "__main__":
    hash = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(6))
    dbtype = 'mysq'
    indir = sys.argv[1]
    outdir = sys.argv[2]
    dbf = sys.argv[3]
    #dir = '/Users/tel/Documents/lab/test/db1/'
    #dir = '/home/tel/benchmark/dunbrack'
    #dir = '/home/tel/test/db1'
    #dbf = 'dunbrack.db'
    path = os.path.join(indir, dbf)
    tmppath = os.path.join('/tmp', hash+dbf)
    try:
        os.remove(tmppath)
    except OSError:
        pass
    db = create_engine('sqlite:///' + tmppath)
#        db.execute('pragma main.page_size=4096')
#        db.execute('pragma main.lock_mode=EXCLUSIVE')
#        db.execute('pragma main.synchronous=NORMAL')
#        db.execute('pragma main.journal_mode=WAL')
#        db.execute('pragma main.cache_size=10000')
#        db.execute('pragma main.temp_store=MEMORY')
    event.listen(db, 'connect', _fk_pragma_on_connect)
    session = scoped_session(sessionmaker(bind=db))
    meta= MetaData(db)
    
    threads = []
    walker = os.walk(indir)
    rootwalk = walker.next()
    rootdir = rootwalk[0]
    rootsubdirs = rootwalk[1]
    numthreads = 1
    lock = threading.Lock()
    event = threading.Event()
    MakeAncilDB(meta=meta,db=db,session=session,csadir=indir,lock=lock,event=event)
#        t = threading.Thread(target=MakeDB, kwargs={'meta':meta,'db':db,'session':session,'rootdir':rootdir,'protdirs':protdirs,'clevels':clevels, 'lock':lock, 'event':event})
#        threads.append(t)
#        t.start()
#        event.wait()
#    while threading.enumerate()>0:
#        time.sleep(5)
    shutil.move(tmppath, path)